<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/blog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-kuai.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-kuai.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="响应式,Dep,Watcher,observe,Observer,defineReactive,">










<meta name="keywords" content="响应式,Dep,Watcher,observe,Observer,defineReactive">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue 响应式原理">
<meta property="og:url" content="http://liukuai.gitee.io/blog/2023/08/10/Vue 响应式原理/index.html">
<meta property="og:site_name" content="LK">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/Dep.png">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/%E9%80%92%E5%BD%92%E8%B0%83%E7%94%A8.png">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/%E6%94%B9%E5%86%99%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95.png">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/Dep.png">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/vue3%E5%93%8D%E5%BA%94%E5%BC%8F.jpg">
<meta property="og:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/vue3%E5%93%8D%E5%BA%94%E5%BC%8F%E6%BA%90%E7%A0%81.jpg">
<meta property="og:updated_time" content="2023-08-16T07:07:51.519Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Vue 响应式原理">
<meta name="twitter:image" content="http://liukuai.gitee.io/blog/2023/08/10/Vue%20响应式原理/Dep.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://liukuai.gitee.io/blog/2023/08/10/Vue 响应式原理/">





  <title>Vue 响应式原理 | LK</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <a href="https://github.com/Luke19950111" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">LK</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">LK loves money.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-navigation">
          <a href="/blog/navigation/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-globe"></i> <br>
            
            导航
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://liukuai.gitee.io/blog/blog/2023/08/10/Vue 响应式原理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lk大大">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="LK">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Vue 响应式原理</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2023-08-10T09:50:56+08:00">
                2023-08-10
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/vue/" itemprop="url" rel="index">
                    <span itemprop="name">vue</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <img src="/blog/2023/08/10/Vue%20响应式原理/Dep.png" title="阅读源码理解响应式原理">
<a id="more"></a>

<h1 id="Vue2"><a href="#Vue2" class="headerlink" title="Vue2"></a>Vue2</h1><p><a href="https://github.com/Luke19950111/vue2-data-reactive" target="_blank" rel="noopener">Vue2 响应式实现</a></p>
<h2 id="将对象属性转为响应式"><a href="#将对象属性转为响应式" class="headerlink" title="将对象属性转为响应式"></a>将对象属性转为响应式</h2><p>首先需要将普通对象转为每个层级的属性都是响应式（可被侦测的）的对象，用到三个方法和类：</p>
<ul>
<li>函数 observe：接收对象，判断是否有 <code>__ob__</code> 属性（Observer类的实例），如果有直接返回该属性，没有则创建 <code>Observer</code> 实例返回</li>
<li>Observer 类：遍历对象属性执行 <code>defineReactive</code>，将一个普通 object 每个层级的属性都变为响应式</li>
<li>函数 defineReactive：使用 <code>Object.defineProperty</code> 将对象属性变为 getter、setter，并对该子属性也调用 <code>observe</code> 函数</li>
</ul>
<p>由此形成递归，这个递归不是自己调用自己，而是由 observe、Observer、defineReactive 三个函数和类循环调用形成（<code>observe =&gt; Observer =&gt; defineReactive =&gt; observe...</code>）</p>
<p>递归调用如下图示：<br><img src="%E9%80%92%E5%BD%92%E8%B0%83%E7%94%A8.png" alt></p>
<p>简单代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// observe.s</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Observer <span class="keyword">from</span> <span class="string">'./Observer.js'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">observe</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> value !== <span class="string">'object'</span>) <span class="keyword">return</span></span><br><span class="line">  <span class="keyword">var</span> ob</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> value.__ob__ !== <span class="string">'undefined'</span>) &#123;</span><br><span class="line">    ob = value.__ob__</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    ob = <span class="keyword">new</span> Observer(value)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> ob</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Observe.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; def &#125; <span class="keyword">from</span> <span class="string">'./utils.js'</span></span><br><span class="line"><span class="keyword">import</span> defineReactive <span class="keyword">from</span> <span class="string">'./defineReactive.js'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Observer</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span> (value) &#123;</span><br><span class="line">    <span class="comment">// 将 Observer 实例设为 value 的 __ob__ 属性</span></span><br><span class="line">    def(value, <span class="string">'__ob__'</span>, <span class="keyword">this</span>, <span class="literal">false</span>)</span><br><span class="line">    <span class="comment">// Observer 类的目的是：将一个普通的 object 每个层级的属性都变为响应式</span></span><br><span class="line">    <span class="keyword">this</span>.walk(value)</span><br><span class="line">  &#125;</span><br><span class="line">  walk (value) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> k <span class="keyword">in</span> value) &#123;</span><br><span class="line">      defineReactive(value, k)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// defineReactive.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> observe <span class="keyword">from</span> <span class="string">'./observe.js'</span></span><br><span class="line"> <span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span> (<span class="params">data, key, val</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'defineReactive'</span>, key)</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">arguments</span>.length == <span class="number">2</span>) &#123;</span><br><span class="line">    val = data[key]</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 对子元素调用 observe，形成递归。这个递归不是自己调用自己，而是多个函数、类循环调用形成（observe =&gt; Observer =&gt; definReactive =&gt; observe...）</span></span><br><span class="line">  <span class="keyword">let</span> childOb = observe(val)</span><br><span class="line"></span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(data, key, &#123;</span><br><span class="line">    enumerable: <span class="literal">true</span>,</span><br><span class="line">    configurable: <span class="literal">true</span>,</span><br><span class="line">    <span class="keyword">get</span>() &#123;</span><br><span class="line">      <span class="keyword">return</span> val</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span>(newValue) &#123;</span><br><span class="line">      <span class="keyword">if</span> (val === newValue) &#123;</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      val = newValue</span><br><span class="line">      <span class="comment">// 当设置了新值，新值也要被 observe，新值可能也是一个对象</span></span><br><span class="line">      childOb = observe(newValue)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h2 id="数组的响应式处理"><a href="#数组的响应式处理" class="headerlink" title="数组的响应式处理"></a>数组的响应式处理</h2><ul>
<li>上文写到在 <code>Observer</code> 类中遍历对象属性，调用 defineReactive，进而使用 Object.defineProperty 将其转为 getter、setter</li>
<li>对于数组类型，在 Observer 类中直接遍历其元素调用 observe 函数，形成递归</li>
<li>将七个会改变原数组的方法改写，并插入到原型链中<ul>
<li>以 Array.prototype 为原型创建对象 arrayMethods： <code>const arrayMethods = Object.create(arrayPrototype)</code></li>
<li>在 <code>arrayMethod</code> 对象上改写七个数组方法</li>
<li>在 Observer 类里判断，如果处理的属性是数组，将改数组的原型改为 arrayMethods：<code>Object.setPrototypeOf(arr, arrayMethods)</code> 相当于 <code>arr.__proto__ = arrayMethods</code></li>
<li>push、unshift、splice 可能往数组里插入新元素，需要对新元素也调用 observe</li>
</ul>
</li>
</ul>
<p>改变数组原型链：<br><img src="%E6%94%B9%E5%86%99%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95.png" alt></p>
<p>现在代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Observer.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; def &#125; <span class="keyword">from</span> <span class="string">'./utils.js'</span></span><br><span class="line"><span class="keyword">import</span> defineReactive <span class="keyword">from</span> <span class="string">'./defineReactive.js'</span></span><br><span class="line"><span class="keyword">import</span> &#123; arrayMethods &#125; <span class="keyword">from</span> <span class="string">'./array.js'</span></span><br><span class="line"><span class="keyword">import</span> observe <span class="keyword">from</span> <span class="string">'./observe.js'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Observer</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span> (value) &#123;</span><br><span class="line">    <span class="comment">// 将 Observer 实例设为 value 的 __ob__ 属性</span></span><br><span class="line">    def(value, <span class="string">'__ob__'</span>, <span class="keyword">this</span>, <span class="literal">false</span>)</span><br><span class="line">    <span class="comment">// Observer 类的目的是：将一个普通的 object 每个层级的属性都变为响应式</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(value)) &#123;</span><br><span class="line">      <span class="comment">// 如果是数组，将数组原型指向改写数组方法后的 arrayMethods</span></span><br><span class="line">      <span class="built_in">Object</span>.setPrototypeOf(value, arrayMethods)</span><br><span class="line">      <span class="keyword">this</span>.observeArray(value)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">this</span>.walk(value)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 遍历对象属性</span></span><br><span class="line">  walk (value) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> k <span class="keyword">in</span> value) &#123;</span><br><span class="line">      defineReactive(value, k)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 遍历数组元素</span></span><br><span class="line">  observeArray (arr) &#123;</span><br><span class="line">    <span class="comment">// 不直接写 i &lt; arr.length，避免特殊情况遍历过程中数组长度变化</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, l = arr.length; i &lt; l; i++) &#123;</span><br><span class="line">      observe(arr[i])</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// array.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> &#123; def &#125; <span class="keyword">from</span> <span class="string">'./utils.js'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 以 Array.prototype 为原型创建对象 arrayMethods</span></span><br><span class="line"><span class="keyword">const</span> arrayPrototype = <span class="built_in">Array</span>.prototype</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> arrayMethods = <span class="built_in">Object</span>.create(arrayPrototype)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 要被改写的7个数组方法</span></span><br><span class="line"><span class="keyword">const</span> methodsNeedChange = [</span><br><span class="line">  <span class="string">'push'</span>,</span><br><span class="line">  <span class="string">'pop'</span>,</span><br><span class="line">  <span class="string">'shift'</span>,</span><br><span class="line">  <span class="string">'unshift'</span>,</span><br><span class="line">  <span class="string">'splice'</span>,</span><br><span class="line">  <span class="string">'sort'</span>,</span><br><span class="line">  <span class="string">'reverse'</span></span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">methodsNeedChange.forEach(<span class="function"><span class="params">methodName</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// 备份原来的方法</span></span><br><span class="line">  <span class="keyword">const</span> original = arrayPrototype[methodName]</span><br><span class="line">  <span class="comment">// 定义新的方法</span></span><br><span class="line">  def(arrayMethods, methodName, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 最外层传入 observe 的 data 一定是对象，第一次遍历 data 对象时给所有的第一层根属性都调用了 observe，所以数组上一定有 __ob__</span></span><br><span class="line">    <span class="keyword">const</span> ob = <span class="keyword">this</span>.__ob__</span><br><span class="line">    <span class="comment">// push、unshift、splice 能够插入新元素，要把插入的新元素也 observe</span></span><br><span class="line">    <span class="keyword">const</span> args = [...arguments]</span><br><span class="line">    <span class="keyword">let</span> inserted = []</span><br><span class="line">    <span class="keyword">switch</span> (methodName) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'push'</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">'unshift'</span>:</span><br><span class="line">        inserted = args</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">      <span class="keyword">case</span> <span class="string">'splice'</span>:</span><br><span class="line">        inserted = args.slice(<span class="number">2</span>)</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (inserted.length) &#123;</span><br><span class="line">      ob.observeArray(inserted)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">`调用改写后的数组方法<span class="subst">$&#123;methodName&#125;</span>`</span>)</span><br><span class="line">    <span class="keyword">const</span> result = original.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>) <span class="comment">// this 就是调用方法的数组</span></span><br><span class="line">    <span class="keyword">return</span> result</span><br><span class="line">  &#125;, <span class="literal">false</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Watcher类和Dep类"><a href="#Watcher类和Dep类" class="headerlink" title="Watcher类和Dep类"></a>Watcher类和Dep类</h2><p>通过<code>Watcher</code>类和<code>Dep</code>类实现依赖收集、添加订阅、通知更新</p>
<ul>
<li>Dep 类：把依赖收集的代码封装成一个 Dep 类，用来管理依赖，每个 Observer 的实例，属性中都有一个 Dep 的实例 (<code>__ob__.dep</code>)</li>
<li>Watcher 类：Watcher 是一个中介，数据发生变化时通过 Watcher 中转，通知组件</li>
</ul>
<p>依赖是什么？</p>
<p>依赖就是用到数据的地方，什么地方用到数据，什么地方就叫依赖。<br>Vue2 中，每个<strong>组件</strong>有对应的数据，并且每个组件有自己的 Watcher 实例，依赖就是这个 Watcher 实例。</p>
<p>何时收集，何时触发？</p>
<p>在 getter 中收集依赖，在 setter 中触发依赖；<br>Watcher 实例把自己设置到全局的一个指定位置 <code>Dep.target</code>，然后读取数据，触发数据的 getter；<br>用 Dep.target 是否存在，判断是否处于依赖收集阶段；<br>getter 中会从 <code>Dep.target</code> 变量读取<strong>正在读取数据的 Watcher 实例</strong>，把这个 Watcher 实例收集到 Dep 中；<br>Dep 使用<strong>发布订阅模式</strong>，当数发生变化，会循环依赖列表，把列表中所有的 Watcher 实例都通知一遍。<br><code>getter =&gt; dep.depend(); setter =&gt; dep.notify(); 数组用 __ob__.dep.notify()</code></p>
<p>图示如下：<br><img src="Dep.png" alt></p>
<p>代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Dep.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> uid = <span class="number">0</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Dep</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>() &#123;</span><br><span class="line">    <span class="keyword">this</span>.id = uid++</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 每个 dep 实例用数组存储自己的订阅者，每个订阅者都是 Watcher 的实例</span></span><br><span class="line">    <span class="keyword">this</span>.subs = []</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 添加订阅</span></span><br><span class="line">  addSub(sub) &#123;</span><br><span class="line">    <span class="keyword">this</span>.subs.push(sub)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 通知更新</span></span><br><span class="line">  notify() &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'notify'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 浅拷贝</span></span><br><span class="line">    <span class="keyword">const</span> subs = <span class="keyword">this</span>.subs.slice()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>, l = subs.length; i &lt; l; i++) &#123;</span><br><span class="line">      subs[i].update()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 添加依赖</span></span><br><span class="line">  depend() &#123;</span><br><span class="line">    <span class="comment">// Dep.target 只是一个指定的全局位置，用 window.target 也行，只要是全局唯一</span></span><br><span class="line">    <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">      <span class="keyword">this</span>.addSub(Dep.target)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Watcher.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Dep <span class="keyword">from</span> <span class="string">"./Dep.js"</span></span><br><span class="line"><span class="keyword">var</span> uid = <span class="number">0</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Watcher</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(target, expression, callback) &#123;</span><br><span class="line">    <span class="keyword">this</span>.id = uid++</span><br><span class="line">    <span class="keyword">this</span>.target = target</span><br><span class="line">    <span class="keyword">this</span>.getter = parsePath(expression)</span><br><span class="line">    <span class="keyword">this</span>.callback = callback</span><br><span class="line">    <span class="keyword">this</span>.value = <span class="keyword">this</span>.get()</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">get</span>() &#123;</span><br><span class="line">    <span class="comment">// 进入依赖收集阶段。将当前 watcher 实例设置到 Dep.target，Dep.target 有值则进入依赖收集阶段</span></span><br><span class="line">    Dep.target = <span class="keyword">this</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> obj = <span class="keyword">this</span>.target</span><br><span class="line">    <span class="keyword">var</span> value</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      value = <span class="keyword">this</span>.getter(obj)</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      Dep.target = <span class="literal">null</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> value</span><br><span class="line">  &#125;</span><br><span class="line">  update() &#123;</span><br><span class="line">    <span class="keyword">this</span>.run()</span><br><span class="line">  &#125;</span><br><span class="line">  run() &#123;</span><br><span class="line">    <span class="keyword">this</span>.getAndInvoke(<span class="keyword">this</span>.callback)</span><br><span class="line">  &#125;</span><br><span class="line">  getAndInvoke(cb) &#123;</span><br><span class="line">    <span class="keyword">const</span> value = <span class="keyword">this</span>.get()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (value !==<span class="keyword">this</span>.value || <span class="keyword">typeof</span> value == <span class="string">'object'</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> oldValue = <span class="keyword">this</span>.value</span><br><span class="line">      <span class="keyword">this</span>.value = value</span><br><span class="line">      cb.call(<span class="keyword">this</span>.target, value, oldValue)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parsePath</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// a.b.c.d</span></span><br><span class="line">  <span class="keyword">var</span> segments = str.split(<span class="string">'.'</span>)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="function">(<span class="params">obj</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; segments.length; i++) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!obj) <span class="keyword">return</span></span><br><span class="line">      obj = obj[segments[i]]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Observer.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Dep <span class="keyword">from</span> <span class="string">'./Dep.js'</span></span><br><span class="line">  <span class="comment">//...</span></span><br><span class="line">  <span class="keyword">constructor</span> (value) &#123;</span><br><span class="line">    <span class="comment">// 每个 Observer 实例，都有一个属性是 Dep 的实例</span></span><br><span class="line">    <span class="keyword">this</span>.dep = <span class="keyword">new</span> Dep()</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// array.js</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//...</span></span><br><span class="line">def(arrayMethods, methodName, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 最外层传入 observe 的 data 一定是对象，第一次遍历 data 对象时给所有的第一层根属性都调用了 observe，所以数组上一定有 __ob__</span></span><br><span class="line">    <span class="keyword">const</span> ob = <span class="keyword">this</span>.__ob__ <span class="comment">// this 就是调用方法的数组</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line"></span><br><span class="line">    ob.dep.notify()</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// defineReactive.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Dep <span class="keyword">from</span> <span class="string">'./Dep.js'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// defineReactive 闭包中的 dep，和 Observer 实例中的 dep 不是同一个</span></span><br><span class="line"><span class="keyword">const</span> dep = <span class="keyword">new</span> Dep()</span><br><span class="line"></span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">get</span>() &#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如果处于依赖收集阶段</span></span><br><span class="line">  <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">    dep.depend()</span><br><span class="line">    <span class="keyword">if</span> (childOb) &#123;</span><br><span class="line">      childOb.dep.depend()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> val</span><br><span class="line">&#125;,</span><br><span class="line"><span class="keyword">set</span>(newValue) &#123;</span><br><span class="line">    <span class="comment">// 发布订阅模式，触发 set 是通知</span></span><br><span class="line">    dep.notify()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Watcher(obj, <span class="string">'a.b.c'</span>, (val, oval) =&gt; &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(val, <span class="string">'nval'</span>)</span><br><span class="line">  <span class="built_in">console</span>.log(oval, <span class="string">'oval'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h1 id="Vue3"><a href="#Vue3" class="headerlink" title="Vue3"></a>Vue3</h1><h2 id="主要工作流程"><a href="#主要工作流程" class="headerlink" title="主要工作流程"></a>主要工作流程</h2><ol>
<li><strong>响应式简单理解就两步： <code>track</code> + <code>trigger</code>，中文含义为跟踪 +　触发</strong><ul>
<li>跟踪（track）：也就是依赖收集，对于响应式数据，找到依赖于该数据的<strong>副作用函数</strong>，然后使用一个方便存储的结构存储对应关系</li>
<li>触发（trigger）：当监听到响应式数据变化时，就在之前收集的存储桶里找到相关的副作用函数，然后执行</li>
</ul>
</li>
<li><strong>为了自动触发，使用 Proxy 代理响应式对象 <code>ReactiveObject</code></strong><ul>
<li>将 track 函数放入了 get，使用该数据时会自动触发 <code>track()</code></li>
<li>将 trigger 函数放入了 set，使用该数据时会自动触发 <code>trigger()</code></li>
</ul>
</li>
<li><strong>为了避免硬编码函数名，每次在 track 时都需要知道副作用函数的名字</strong><ul>
<li>使用全局变量 <code>activeEffect</code> 来代替，及 track 函数每次收集 <code>activeEffect</code> 变量所指向的函数 （取 activeEffect 变量）</li>
<li>然后通过 <code>ReactiveEffect</code> 注册传递过来的副作用函数，将 <code>activeEffect</code> 变量指向该副作用函数 （把当前副作用函数赋值给 activeEffect 变量）</li>
</ul>
</li>
</ol>
<p>下面介绍具体一点的工作链路。</p>
<p><img src="vue3%E5%93%8D%E5%BA%94%E5%BC%8F.jpg" alt></p>
<p><strong>工作过程：</strong></p>
<ol start="0">
<li>首先有一个响应式数据 <code>ReactiveObject{}</code> 和依赖于该数据的一个副作用函数 <code>Effect()</code></li>
<li>将副作用函数传递到 <code>ReactiveEffect</code> 函数中</li>
<li>注册该副作用函数，将 <code>activeEffect</code> 变量指向它</li>
<li>执行该副作用函数</li>
<li>由于该副作用函数依赖于响应式数据 <code>ReactiveObject</code>，并且已经为 <code>ReactiveObject</code> 设置了代理拦截操作 <code>get</code>，故在读取该值时会触发 <code>track</code> 函数</li>
<li>track 函数找到 <code>activeEffect</code> 变量，此时指向的正是需要的 <code>Effect</code> 函数</li>
<li>将属性值与副作用函数绑定关系并存储</li>
<li><code>activeEffect = null</code> 方便后续调用</li>
</ol>
<p>当我们更新了响应式数据中断值后，由于已经为 <code>ReactiveObject</code> 设置了代理拦截操作 <code>set</code>，故会在我们设置该对象属性值时自动触发 <code>trigger</code> 函数</p>
<ol start="8">
<li>找到属性值依赖的副作用函数</li>
<li>执行副作用函数完成自动更新</li>
</ol>
<h2 id="核心代码"><a href="#核心代码" class="headerlink" title="核心代码"></a>核心代码</h2><p>核心代码实现如下图：</p>
<p><img src="vue3%E5%93%8D%E5%BA%94%E5%BC%8F%E6%BA%90%E7%A0%81.jpg" alt></p>
<h1 id="Vue2-和-Vue3-响应式比较"><a href="#Vue2-和-Vue3-响应式比较" class="headerlink" title="Vue2 和 Vue3 响应式比较"></a>Vue2 和 Vue3 响应式比较</h1><ul>
<li><code>vue2</code> 中采用 <code>defineProperty</code> 来劫持整个对象，然后进行深度遍历所有属性，给每个属性添加 <code>getter</code> 和 <code>setter</code>，实现响应式</li>
<li><code>vue3</code> 采用 <code>proxy</code> 重写了响应式系统，因为 <code>proxy</code> 可以对整个对象进行监听，所以不需要深度遍历<ul>
<li>可以动态监听属性的添加</li>
<li>可以监听到数组的索引和数组 <code>length</code> 属性</li>
<li>可以监听删除属性</li>
</ul>
</li>
<li>vue2 和 vue3 的响应式实现也有类似之处<ul>
<li>先将数据转换为响应式数据（分别用 <code>defineProperty</code> 和 <code>Proxy</code>）</li>
<li>都在 get 中收集依赖，在 set 中触发依赖（依赖分别为 <strong>Watcher 实例</strong> 和<strong>副作用函数</strong>）</li>
<li>依赖收集过程中都将需要的函数设置为一个全局变量（分别为 <code>Dep.target</code> 和 <code>activeEffect</code> 变量）</li>
</ul>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/响应式/" rel="tag"><i class="fa fa-tag"></i> 响应式</a>
          
            <a href="/blog/tags/Dep/" rel="tag"><i class="fa fa-tag"></i> Dep</a>
          
            <a href="/blog/tags/Watcher/" rel="tag"><i class="fa fa-tag"></i> Watcher</a>
          
            <a href="/blog/tags/observe/" rel="tag"><i class="fa fa-tag"></i> observe</a>
          
            <a href="/blog/tags/Observer/" rel="tag"><i class="fa fa-tag"></i> Observer</a>
          
            <a href="/blog/tags/defineReactive/" rel="tag"><i class="fa fa-tag"></i> defineReactive</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2023/08/08/webview 中页面内存优化/" rel="next" title="webview 中页面内存优化">
                <i class="fa fa-chevron-left"></i> webview 中页面内存优化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2023/12/25/框架的运行时和编译时/" rel="prev" title="框架的运行时和编译时">
                框架的运行时和编译时 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
            <a href="/blog/" class="site-author-image" rel="start" style="border:none">
              <img class="site-author-image" itemprop="image" src="/blog/images/avatar.jpg" alt="lk大大">
            </a>
            
              <p class="site-author-name" itemprop="name">lk大大</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">87</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">181</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/luke19950111" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:lukelovenoney@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/b293f4ffc5fc" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-edit"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/3699074360/profile?topnav=1&wvr=6&is_all=1" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://humanwhocodes.com/blog/2007/08/15/what-makes-a-good-front-end-engineer/" title="What makes a good front end engineer" target="_blank">What makes a good front end engineer</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="Web前端导航" target="_blank">Web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://read.douban.com/reader/ebook/7412854/" title="Three.js入门指南（张雯莉）" target="_blank">Three.js入门指南（张雯莉）</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.npmjs.cn/" title="npm中文文档" target="_blank">npm中文文档</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.nodeapp.cn/" title="node.js中文" target="_blank">node.js中文</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://webpack.js.org/" title="webpack" target="_blank">webpack</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://cn.vuejs.org/v2/guide/" title="vue文档" target="_blank">vue文档</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wangdoc.com/javascript/" title="JS参考教程（阮一峰）" target="_blank">JS参考教程（阮一峰）</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://es6.ruanyifeng.com/" title="ES6教程（阮一峰）" target="_blank">ES6教程（阮一峰）</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue2"><span class="nav-number">1.</span> <span class="nav-text">Vue2</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#将对象属性转为响应式"><span class="nav-number">1.1.</span> <span class="nav-text">将对象属性转为响应式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数组的响应式处理"><span class="nav-number">1.2.</span> <span class="nav-text">数组的响应式处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Watcher类和Dep类"><span class="nav-number">1.3.</span> <span class="nav-text">Watcher类和Dep类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue3"><span class="nav-number">2.</span> <span class="nav-text">Vue3</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#主要工作流程"><span class="nav-number">2.1.</span> <span class="nav-text">主要工作流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#核心代码"><span class="nav-number">2.2.</span> <span class="nav-text">核心代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue2-和-Vue3-响应式比较"><span class="nav-number">3.</span> <span class="nav-text">Vue2 和 Vue3 响应式比较</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lk大大</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
 -->



<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共56.5k字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 访问总量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>

<!-- 页面点击跳字 -->
<script type="text/javascript" src="/blog/js/src/custom.js"></script>
